package web.servlet;

import com.alibaba.fastjson.JSON;
import entity.*;
import org.apache.log4j.Logger;
import service.BaseGoodsService;
import service.FocussService;
import service.impl.BaseGoodsServiceImpl;
import service.impl.FocussServiceImpl;
import web.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2017/11/13.
 */
@WebServlet("/eshopServlet/*")
public class EshopServlet extends BaseServlet {
    @RequestMapping("/dispatcher")
    public void dispatcher(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符编码
        request.setCharacterEncoding("utf-8");
        response.sendRedirect("/eshopServlet/query");
}
    @RequestMapping("/query")
    public void query(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        //设置字符编码
        request.setCharacterEncoding("utf-8");
        //调用业务方法
        BaseGoodsService bgs=new BaseGoodsServiceImpl();
        try {
            List<BaseGoodsEntity> list=bgs.query();
            //将集合放入到request范围中
            request.setAttribute("LIST",list);
            //处理轮播图
            //1.调用业务方法
            FocussService fs=new FocussServiceImpl();
            List<FocussEntity> img=fs.queryImg();
            //2.将图片存入到request中
            request.setAttribute("IMG",img);
            //处理新品上架
            //1.调用业务方法
            List<BaseGoodsEntity> listnew=bgs.queryNew();
            //2.将查出来的新品存放在request中
            request.setAttribute("LISTNEW",listnew);
            //请求转发到index.jsp页面
            request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request,response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/details")
    public void details(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        //设置编码
        request.setCharacterEncoding("utf-8");
        //得到参数
        String goodsid=request.getParameter("goodsid");
        long gd=Long.valueOf(goodsid);
        //调用业务方法
        BaseGoodsService bs=new BaseGoodsServiceImpl();
        try {
            DetailEntity de=bs.queryDetails(gd);
            String detail=de.getDetail();
            String[] details=detail.split(",");
            //将实体放到request中
            request.setAttribute("DETAILS",details);
            request.setAttribute("ENTITY",de);
            //处理区域和店铺
            //1.调用业务方法
            List<AreaEntity> area=bs.queryArea();
            //2.将区域放入到request中
            request.setAttribute("AREA",area);
            request.getRequestDispatcher("/WEB-INF/views/detail.jsp").forward(request,response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*
    * 注册
    */
    @RequestMapping("/register")
    public void register(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        //设置编码
        request.setCharacterEncoding("utf-8");
        //得到参数
        String userAccount=request.getParameter("username");
        String userPassword=request.getParameter("password");
        String comfirmpwd=request.getParameter("rqpwd");
        String imgCode=request.getParameter("imgcode");
        String messageCode=request.getParameter("dxyzm");
        //判断密码
        if(!userPassword.equals(comfirmpwd)){
            request.setAttribute("MSG","两次密码不一样");
            response.sendRedirect("/register.jsp");
            return;
        }
        //判断输入的验证码是否和图片验证码相同
        String kaptchaCode=(String) request.getSession().getAttribute("IMAGE_CODE");
        if(imgCode==null|| !(imgCode.equalsIgnoreCase(kaptchaCode))){
            request.setAttribute("ERROR","图片验证码输入错误");
            response.sendRedirect("/register.jsp");
            return;
        }
        //从session中取出短信验证实体
        MessageEntity me=(MessageEntity) request.getSession().getAttribute(MSG_TOKEN_IN_SESSION);
        //从实体中取出获取的短信验证码
        String messagecode=me.getIdentifyCode();
        //判断用户输入的短信验证码和获取的验证码是否一致
        if(!(messageCode.equals(messagecode))){
            request.setAttribute("MC","短信验证码错误！");
            response.sendRedirect("/register.jsp");
            return;
        }
        try {
            //调用业务方法
            BaseGoodsService bgs=new BaseGoodsServiceImpl();
            int r=bgs.register(userAccount,userPassword);
            //数据全都验证成功，跳转到登录界面
            response.sendRedirect("/login.jsp");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*
    *得到短信验证码
     */
    //将实体中的电话号码放到session中
    public static final String MSG_TOKEN_IN_SESSION="MSG_TOKEN_IN_SESSION";
    @RequestMapping("/getMessageCode")
    public void getMessageCode(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        Logger logger=Logger.getLogger(EshopServlet.class);
        //得到json传过来的电话号码
        String phoneNumber=request.getParameter("phone");
        //从session中取出实体
        HttpSession hs=request.getSession();
        MessageEntity me=(MessageEntity) hs.getAttribute(MSG_TOKEN_IN_SESSION);
        //判断实体是否存在
        if(me!=null){
            //已经存在
            long diff=System.currentTimeMillis()-me.getTime();
            if(diff<60*1000){
                //错误，不允许发送短信验证码
                Map<String,Object> result= new HashMap<>();
                result.put("success",false);
                result.put("msg","验证码已发送");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(result));
                return;
            }
        }
        //如果不存在,创建实体
        me=new MessageEntity();
        me.setTime(System.currentTimeMillis());
        me.setPhoneNumber(phoneNumber);
        //得到验证码
        String msgCode=getMsgCode();
        me.setIdentifyCode(msgCode);
        logger.info("短信验证码："+msgCode);
        hs.setAttribute(MSG_TOKEN_IN_SESSION,me);
        //将成功信息放入到map中
        Map<String,Object> result= new HashMap<>();
        result.put("success",true);
        result.put("msg","验证码已发送");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));

    }

    //随机获取短信验证码
    private String getMsgCode(){
        String number="0123456789";
        Random r=new Random(System.currentTimeMillis());
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<6;i++){
            int index=r.nextInt(number.length());
            sb.append(number.charAt(index));
        }
        return sb.toString();
    }
    @RequestMapping("/login")
    public void login(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        //设置参数
        request.setCharacterEncoding("utf-8");
        //得到参数
        String userAccount=request.getParameter("username");
        String userPwd=request.getParameter("password");
        //判断用户名和密码
        if(userAccount==null||"".equals(userAccount)){
            request.setAttribute("notaccount","用户名错误");
            response.sendRedirect("/login.jsp");
            return;
        }
        if(userPwd==null||"".equals(userPwd)){
            request.setAttribute("notpwd","密码错误");
            response.sendRedirect("/login.jsp");
            return;
        }
        //调用业务方法
        BaseGoodsService bgs=new BaseGoodsServiceImpl();
        try {
            UserEntity ue=bgs.login(userAccount,userPwd);
            //将实体放入到session中
            request.getSession().setAttribute("USER",ue);
            //跳转
            response.sendRedirect("/index.jsp");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 购物车部分
     */
    //查询
    @RequestMapping("/queryAll")
    public void queryAll(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        //设置参数
        request.setCharacterEncoding("utf-8");
        //调用业务方法
        BaseGoodsService mbgs=new BaseGoodsServiceImpl();
        try {
            List<GoodsEntity> list=mbgs.queryAll();
            //将集合放到request中
            request.setAttribute("CARTLIST",list);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/add")
    public void add(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        //设置编码
        request.setCharacterEncoding("utf-8");
        //得到参数
        String goodsId=request.getParameter("goodsId");
        long goodsid=Integer.valueOf(goodsId);
        //调用业务方法
        BaseGoodsService bgs=new BaseGoodsServiceImpl();
        try {
            GoodsEntity goods=bgs.queryById(goodsid);
            //从session中取出购物车
            ShopCartEntity sce=(ShopCartEntity) request.getSession().getAttribute("shopCart");
            if(sce==null){
                sce=new ShopCartEntity();
                //将购物车放到session中
                request.getSession().setAttribute("shopCart",sce);
            }
            sce.add(goods);

            response.sendRedirect(request.getContextPath()+"/eshopServlet/show");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/show")
    public void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/see.jsp").forward(request,response);
    }

    /**
     * 修改数量
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/updateCount")
    public void updateCount(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //得到参数
        String goodsId=request.getParameter("goodsId");
        String count=request.getParameter("count");
        long goodsid=Long.valueOf(goodsId);
        int counts=Integer.valueOf(count);
        //从Session中取出购物车
        ShopCartEntity shopCart=(ShopCartEntity)(request.getSession().getAttribute("shopCart"));
        try {
            if(shopCart!=null){
                BaseGoodsService bgs=new BaseGoodsServiceImpl();
                    //调用修改方法
                    int r=bgs.updateCount(goodsid,counts);
                    Map<String,Object> map=new HashMap<>();
                    map.put("success",true);
                    map.put("total",getTotalPrice( request, response));
                    String result= JSON.toJSONString(map);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(result);
    }else{
        Map<String,Object> map=new HashMap<>();
        map.put("success",false);
        String result= JSON.toJSONString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(result);
    }

} catch (ClassNotFoundException e) {
        e.printStackTrace();
        } catch (SQLException e) {
        e.printStackTrace();
        }
    }

    //计算总价
    public double getTotalPrice(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
        String goodsId=request.getParameter("goodsId");
        long goodsid=Long.valueOf(goodsId);
        //调用方法
        BaseGoodsService bgs=new BaseGoodsServiceImpl();
        double total=0.00;
        try {
            GoodsEntity list=bgs.queryCount(goodsid);
            //取出价格和数量
            double price=list.getSale_price();
            int count=list.getCounts();
            total=price*count;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return total;
    }
















}
